package com.ruoyi.activiti.service;

import cn.hutool.core.collection.CollectionUtil;
import com.ruoyi.activiti.domain.MyHistoricTask;
import com.ruoyi.activiti.domain.MyProcessInstanceCondition;
import com.ruoyi.activiti.domain.TaskVo;
import com.ruoyi.activiti.mapper.TaskMapper;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.domain.SysUser;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricTaskInstanceQuery;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author scihi
 */
@Service
@Transactional
public class ProcessInstanceService {

    @Autowired
    private TaskService taskService;
    @Autowired
    private MyTaskService myTaskService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskMapper taskMapper;
    @Autowired
    private RemoteUserService remoteUserService;

    public void delegate(String taskId, String fromUser, String delegateToUser) {
        taskService.delegateTask(taskId, delegateToUser);
    }

    public void cancelApply(String instanceId, String deleteReason) {
        // 执行此方法后未审批的任务 act_ru_task 会被删除，流程历史 act_hi_taskinst 不会被删除，并且流程历史的状态为finished完成
        runtimeService.deleteProcessInstance(instanceId, deleteReason);
    }

    public void suspendOrActiveApply(String instanceId, String suspendState) {
        if ("1".equals(suspendState)) {
            // 当流程实例被挂起时，无法通过下一个节点对应的任务id来继续这个流程实例。
            // 通过挂起某一特定的流程实例，可以终止当前的流程实例，而不影响到该流程定义的其他流程实例。
            // 激活之后可以继续该流程实例，不会对后续任务造成影响。
            // 直观变化：act_ru_task 的 SUSPENSION_STATE_ 为 2
            runtimeService.suspendProcessInstanceById(instanceId);
        } else if ("2".equals(suspendState)) {
            runtimeService.activateProcessInstanceById(instanceId);
        }
    }

    public List<MyHistoricTask> selectHistoryList(String processInstanceId){
        return this.selectHistoryList(processInstanceId, 1, 999999);
    }

    public List<MyHistoricTask> selectHistoryList(String processInstanceId, Integer pageNum, Integer pageSize) {
        HistoricTaskInstanceQuery query = historyService.createHistoricTaskInstanceQuery();
        List<HistoricTaskInstance> list = query.processInstanceId(processInstanceId)
                //.activityType("userTask")
                .orderByDueDateNullsFirst().desc()
                .listPage((pageNum - 1) * pageSize, pageSize);
        if(CollectionUtil.isEmpty(list)){
            return new ArrayList<>(0);
        }
        List<MyHistoricTask> newList = new ArrayList<>(list.size());
        list.forEach(act -> {
            MyHistoricTask activity = new MyHistoricTask();
            BeanUtils.copyProperties(act, activity);
            List<MyHistoricTask> comments = taskMapper.queryComments(act.getId());
            if (!CollectionUtils.isEmpty(comments)) {
                activity.setAction(comments.get(0).getAction());
                String fullComment = comments.get(0).getComment();
                String[] arr = fullComment.split(":");
                if(arr!=null && arr.length==1){
                    activity.setActionName(arr[0]);
                }if(arr!=null && arr.length==2){
                    activity.setActionName(arr[0]);
                    activity.setComment(arr[1]);
                }
            }
            if(StringUtils.isNotEmpty(act.getAssignee())){
                R<SysUser> r = remoteUserService.loadCachedUserByUsername(act.getAssignee());
                if (r != null) {
                    activity.setAssigneeName(r.getData().getNickName());
                }
            }
            newList.add(activity);
        });
        //为第一条数据添加处理人信息
        if(StringUtils.isEmpty(newList.get(0).getAssigneeName())){
            TaskVo taskVo = myTaskService.getTaskVoById(newList.get(0).getId());
            if(taskVo!=null){
                newList.get(0).setAssigneeName(taskVo.getState());
            }
        }
        return newList;
    }

    public Long countHistoryList(String processInstanceId) {
        HistoricTaskInstanceQuery query = historyService.createHistoricTaskInstanceQuery();
        long count = query.processInstanceId(processInstanceId).count();
        return count;
    }

    public Set<String> listInstanceIds(MyProcessInstanceCondition condition) {
        return taskMapper.instanceIds(condition);
    }
}
